
function IconPicker(elem, path){
    this.elem = elem = getCtrl(elem);
    this.datalist = getIconList(path);

    this.hide = function(){
        this.div.style.display = 'none'
    }

    this.show = function(){
        this.div.style.display = 'block'
    }

    this.setIcon = function(color){
        elem.style.backgroundImage = color;
        if (strlen(elem.value) > 0){
            elem.value = color.colorHex().toUpperCase();
        }
        this.hide();
    }

    var self = this;
    var pack = $('#IconPickerTable');
    var html = "<table class='IconPickerTable' id='IconPickerTable'>";

    if (pack && strlen(pack.html()) > 64 && navigator.userAgent.indexOf('Firefox') >= 0){
        this.div = pack.parent()[0];
    }
    else{
        var num = 0;
        var cols = (this.datalist.length > 20) ? 8 : 6;
        var rows = Math.ceil(this.datalist.length / cols);

        for (i = 0; i < rows; i++){
            html += "<tr>";

            for (j = 0; j < cols && num < this.datalist.length; j++, num++){
                html += '<td style="background-image:url(' + this.datalist[num] + ')"></td>';
            }

            html+= "</tr>";
        }
        
        html += '</table>';

        this.div = document.createElement('div');
        this.div.innerHTML = html;
    }

    var sz = elem.clientWidth;
    var tds = this.div.getElementsByTagName('td');

    for (var i = 0, l = tds.length ; i < l; i++){
        tds[i].onmousedown = function(e){
            self.setIcon(this.style.backgroundImage);
            elem.blur();
            e.stopPropagation();
        }

        if (tds[i].style.backgroundImage == elem.style.backgroundImage){
            tds[i].style.backgroundColor = 'red';
        }
        else{
            tds[i].style.backgroundColor = '#FFF';
        }
        
        tds[i].style.margin = '0px';
        tds[i].style.padding = '0px';
        tds[i].style.width = sz + 'px';
        tds[i].style.height = sz + 'px';
    }

    elem.parentNode.appendChild(this.div);
    this.div.style.zIndex = 1000;
    this.div.style.position = 'fixed';
    this.div.style.left = getLeft(elem) + 'px'
    this.div.style.top = (elem.clientHeight + getTop(elem) + 1) + 'px';
    elem.onclick = function(){
        if(self.div.style.display == 'none'){
            self.show();
        }
        else{
            self.hide();
       }
    }
}